package me.luger.core.dao.nutz.callback;

import me.luger.core.commom.util.StringUtil;
import me.luger.core.dao.nutz.entity.NutzTransient;
import org.nutz.dao.entity.Entity;
import org.nutz.dao.impl.sql.callback.EntityCallback;
import org.nutz.dao.pager.ResultSetLooping;
import org.nutz.dao.sql.SqlContext;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by a on 2017/1/11.
 */
public class ListEntityCallback extends EntityCallback {

    protected String prefix;
    public ListEntityCallback() {}
    public ListEntityCallback(String prefix) {
        this.prefix = prefix;
    }

    @Override
    protected Object process(final ResultSet rs, final Entity<?> entity, final SqlContext context)
            throws SQLException {
        final Field[] fields = entity.getMirror().getFields(NutzTransient.class);
        ResultSetLooping ing = new ResultSetLooping() {
            protected boolean createObject(int index, ResultSet rs, SqlContext context, int rowCount) {
                Object obj = entity.getObject(rs, null, prefix);
                Method setMethod = null;
                for(Field field : fields){
                    try{
                        NutzTransient nutzTransient = field.getAnnotation(NutzTransient.class);
                        String fieldDbName = StringUtil.isBlank(nutzTransient.value()) ? field.getName() : "";
                        if(StringUtil.isNotBlank(prefix)){
                            fieldDbName = prefix + fieldDbName;
                        }
                        setMethod = entity.getMirror().getSetter(field);
                        Object rsObj = rs.getObject(fieldDbName);
                        if(null != setMethod && null != rsObj){
                            setMethod.invoke(obj,rsObj);
                        }
                    }catch (Exception e){
                        continue;
                    }
                }
                list.add(obj);
                return true;
            }
        };
        ing.doLoop(rs, context);
        return ing.getList();
    }
}